<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="团队名称" prop="teamTeamname">
        <el-input v-model="queryParams.teamTeamname" placeholder="请输入团队名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:team:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:team:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:team:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:team:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teamList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="团队编号" align="center" prop="teamId" />
      <el-table-column label="团队名称" align="center" prop="teamTeamname" />
      <el-table-column label="团队成员" align="center">
        <template slot-scope="scope">
          <div>
            <span v-for="user in scope.row.proTeamUserList" :key="user.userId" style="margin-right: 8px;">
              {{ user.name }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:team:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:team:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改项目团队管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="团队名称" prop="teamTeamname">
          <el-input v-model="form.teamTeamname" placeholder="请输入团队名称" />
        </el-form-item>
        <el-divider content-position="center">项目团队成员信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddProTeamUser">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteProTeamUser">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="proTeamUserList" :row-class-name="rowProTeamUserIndex"
          @selection-change="handleProTeamUserSelectionChange" ref="proTeamUser">
          <el-table-column type="selection" width="80" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="80" />
          <el-table-column label="用户ID" align="center" prop="userId" width="80" />
          <el-table-column label="姓名" prop="name" width="160">
            <template slot-scope="scope">
              <el-select v-model="scope.row.name" placeholder="请选择姓名" @change="updateUserId(scope.row.index, $event)">
                <el-option v-for="item in userList" :key="item.userName" :label="item.userName" :value="item.userName">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="岗位" prop="postId">
            <template slot-scope="scope">
              <el-select v-model="scope.row.postId" placeholder="请选择岗位">
                <el-option v-for="item in postList" :key="item.postId" :label="item.postName" :value="item.postId">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="工作状态" prop="state" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.state" placeholder="请选择工作状态">
                <el-option label="在职" :value="1" />
                <el-option label="离职" :value="2" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="职责" prop="task" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.task" placeholder="请输入职责" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTeam, getTeam, delTeam, addTeam, updateTeam } from "@/api/system/team";
import { listPost } from "@/api/system/post";
import { listUser } from "@/api/system/user";

export default {
  name: "Team",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedProTeamUser: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目团队管理表格数据
      teamList: [],
      // 项目团队成员表格数据
      proTeamUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamTeamname: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        teamTeamname: [
          { required: true, message: "团队名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '团队名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
      },
      postList: [], //岗位
      userList: []
    };
  },
  created() {
    this.getList();
    listPost().then(response => {
      this.postList = response.rows;
    });
    listUser().then(response => {
      this.userList = response.rows;
    });
  },
  methods: {
    // 团队队员重复删除
    removeByIndex(targetIndex) {
      this.proTeamUserList = this.proTeamUserList.filter(item => item.index !== targetIndex);
    },
    // 获取用户ID
    updateUserId(index, selName) {
      const selTeam = this.proTeamUserList.find(user => user.name === selName);
      if (selTeam.index != index) {
        this.$modal.msgError("团队内已添加该成员。");
        this.removeByIndex(index);
        return
      }
      const selectedUser = this.userList.find(user => user.userName === selName);
      if (selectedUser) {
        this.proTeamUserList[index - 1].userId = selectedUser.userId;
      } else {
        console.error(`未找到 "${selName}" 的用户id`);
        this.form.userId = '';
      }
    },
    /** 查询项目团队管理列表 */
    getList() {
      this.loading = true;
      listTeam(this.queryParams).then(response => {
        this.teamList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        teamId: null,
        teamTeamname: null
      };
      this.proTeamUserList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.teamId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目团队管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const teamId = row.teamId || this.ids
      getTeam(teamId).then(response => {
        this.form = response.data;
        this.proTeamUserList = response.data.proTeamUserList;
        this.open = true;
        this.title = "修改项目团队管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.proTeamUserList = this.proTeamUserList;
          if (this.form.teamId != null) {
            updateTeam(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTeam(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const teamIds = row.teamId || this.ids;
      this.$modal.confirm('是否确认删除项目团队管理编号为"' + teamIds + '"的数据项？').then(function () {
        return delTeam(teamIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 项目团队成员序号 */
    rowProTeamUserIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 项目团队成员添加按钮操作 */
    handleAddProTeamUser() {
      let obj = {};
      obj.userId = "";
      obj.name = "";
      obj.postId = "";
      obj.state = "";
      obj.task = "";
      this.proTeamUserList.push(obj);
    },
    /** 项目团队成员删除按钮操作 */
    handleDeleteProTeamUser() {
      if (this.checkedProTeamUser.length == 0) {
        this.$modal.msgError("请先选择要删除的项目团队成员数据");
      } else {
        const proTeamUserList = this.proTeamUserList;
        const checkedProTeamUser = this.checkedProTeamUser;
        this.proTeamUserList = proTeamUserList.filter(function (item) {
          return checkedProTeamUser.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleProTeamUserSelectionChange(selection) {
      this.checkedProTeamUser = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/team/export', {
        ...this.queryParams
      }, `team_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
